import { Button, Descriptions, Modal } from 'antd'
import React, { Fragment, useEffect, useState } from 'react'
import {
  ExclamationCircleOutlined
} from '@ant-design/icons'
import axios from 'axios'
import base from '../../routes/baseUrl'
import { useNavigate } from 'react-router'

const { confirm } = Modal

export default function SelectedTeacher() {

  const [teacherInfo, setTeacherInfo] = useState({})
  const { id, teacherId, changePassword } = JSON.parse(sessionStorage.getItem('token'))
  const navigate = useNavigate()

  useEffect(() => {
    if (teacherId !== 904) {
      axios.get(base + `/teachers/${teacherId}`).then(res => {
        setTeacherInfo(res.data)
      })
    }
  }, [teacherId])

  const showDeleteConfirm = () => {
    confirm({
      title: '确定要退选导师吗？',
      icon: <ExclamationCircleOutlined />,
      content: '注意！退选后只能重新选择导师',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        // console.log(teacherInfo)
        axios.patch(base + `/students/${id}`, { teacherId: 904 }).then(res => {
          // console.log(res.data)
          sessionStorage.setItem('token', JSON.stringify({...res.data, changePassword}))
          setTeacherInfo([])
        })
      },
      onCancel() {
        console.log('操作取消')
      }
    })
  }

  return (
    teacherId !== 904 ? <Fragment>
    <Descriptions title='我的导师' bordered>
      <Descriptions.Item label='工号'>{teacherId}</Descriptions.Item>
      <Descriptions.Item label='导师姓名'>{teacherInfo.name}</Descriptions.Item>
    </Descriptions>
    <br />
    <Button type='danger' onClick={showDeleteConfirm}>退选</Button>
  </Fragment> : <Fragment>
    <h2>你还没有选择导师</h2>
    <Button type='primary' onClick={() => {navigate('/select-teacher')}}>去选择</Button>
  </Fragment>
  )
}
